<template>
  <div class="hold-transition">
    <div id="app" style="width: 85vw;">
      <div class="content-header">
        <h1>用户管理<small>用户信息</small></h1>
        <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>系统管理</el-breadcrumb-item>
          <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <div class="app-container">
        <div class="box">
          <!-- 搜索和操作按钮 -->
          <div class="filter-container">
            <el-input
                placeholder="用户名/邮箱/手机号"
                v-model="pagination.queryString"
                style="width: 200px;"
                class="filter-item"
            ></el-input>
            <el-select v-model="pagination.userType" placeholder="用户类型" clearable style="width: 120px;" class="filter-item">
              <el-option label="管理员" value="管理员" />
              <el-option label="司机" value="司机" />
              <el-option label="客服" value="客服" />
              <el-option label="乘客" value="乘客" />
            </el-select>
            <el-select v-model="pagination.status" placeholder="状态" clearable style="width: 120px;" class="filter-item">
              <el-option label="活跃" value="活跃" />
              <el-option label="禁用" value="禁用" />
              <el-option label="待审核" value="待审核" />
            </el-select>
            <el-button @click="findPage()" class="dalfBut">查询</el-button>
            <el-button type="primary" class="butT" @click="handleCreate()">新建用户</el-button>
          </div>

          <!-- 数据表格 -->
          <el-table
              v-loading="loading"
              size="small"
              current-row-key="userId"
              :data="dataList"
              stripe
              highlight-current-row
          >
            <el-table-column type="index" align="center" label="序号"></el-table-column>
            <el-table-column prop="avatar" label="头像" align="center" width="100">
              <template #default="scope">
                <el-avatar v-if="scope.row.img" :src="scope.row.img" :size="40"></el-avatar>
                <el-avatar v-else :icon="UserFilled" :size="40"></el-avatar>
              </template>
            </el-table-column>
            <el-table-column prop="username" label="用户名" align="center"></el-table-column>
            <el-table-column prop="email" label="邮箱" align="center"></el-table-column>
            <el-table-column prop="phoneNumber" label="手机号" align="center"></el-table-column>
            <el-table-column prop="userType" label="用户类型" align="center">
              <template #default="scope">
                <el-tag :type="getUserTypeTag(scope.row.userType)">{{ scope.row.userType }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" align="center">
              <template #default="scope">
                <el-tag :type="getStatusTag(scope.row.status)">{{ scope.row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="creationTime" label="创建时间" align="center">
              <template #default="scope">
                {{ formatDateTime(scope.row.creationTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="lastLoginTime" label="最后登录" align="center">
              <template #default="scope">
                {{ formatDateTime(scope.row.lastLoginTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="220">
              <template #default="scope">
                <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
                <el-button
                    :type="scope.row.status === '禁用' ? 'success' : 'warning'"
                    size="mini"
                    @click="handleStatusChange(scope.row)"
                >
                  {{ scope.row.status === '禁用' ? '启用' : '禁用' }}
                </el-button>
                <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页组件 -->
          <div class="pagination-container">
            <el-pagination
                class="pagiantion"
                @current-change="findPage"
                :current-page="pagination.currentPage"
                :page-size="pagination.pageSize"
                :total="pagination.total"
                layout="total, prev, pager, next, jumper"
            ></el-pagination>
          </div>

          <!-- 新增/编辑用户弹层 -->
          <el-dialog :title="dialogTitle" v-model="dialogFormVisible">
            <el-form ref="dataForm" :model="formData" :rules="rules" label-position="right" label-width="100px">
              <el-row>
                <el-col :span="24">
                  <el-form-item label="头像" prop="avatar">
                    <el-upload
                        class="avatar-uploader"
                        action="/admin/upload"
                        :headers="headers"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :on-error="handleAvatarError"
                        :before-upload="beforeAvatarUpload"
                        name="file"
                    >
                      <img v-if="formData.img" :src="formData.img" class="avatar">
                      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="用户名" prop="username" @blur="checkUsernameExists">
                    <el-input v-model="formData.username" :disabled="dialogStatus === 'update'"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="密码" prop="password" v-if="dialogStatus === 'create'">
                    <el-input v-model="formData.password" type="password"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="邮箱" prop="email" @blur="checkEmailExists">
                    <el-input v-model="formData.email"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="手机号" prop="phoneNumber" @blur="checkPhoneExists">
                    <el-input v-model="formData.phoneNumber"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="用户类型" prop="userType">
                    <el-select v-model="formData.userType">
                      <el-option label="管理员" value="管理员"></el-option>
                      <el-option label="司机" value="司机"></el-option>
                      <el-option label="客服" value="客服"></el-option>
                      <el-option label="乘客" value="乘客"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="状态" prop="status">
                    <el-select v-model="formData.status">
                      <el-option label="活跃" value="活跃"></el-option>
                      <el-option label="禁用" value="禁用"></el-option>
                      <el-option label="待审核" value="待审核"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <template #footer>
<span class="dialog-footer">
    <el-button @click="dialogFormVisible = false">取消</el-button>
<el-button type="primary" @click="handleEditOrAdd">确定</el-button>
</span>
            </template>
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, UserFilled } from '@element-plus/icons-vue';
import service from '@/util/http';

// 表单引用和加载状态
const dataForm = ref(null);
const loading = ref(false);
const dialogFormVisible = ref(false);
const dialogStatus = ref('create');
const dialogTitle = computed(() => dialogStatus.value === 'create' ? '新增用户' : '编辑用户');

// 添加headers配置
const headers = {
  Authorization: localStorage.getItem('token') || ''
};

// 数据列表
const dataList = ref([]);

// 表单数据
const formData = reactive({
  userId: null,
  username: '',
  password: '',
  email: '',
  phoneNumber: '',
  userType: '',
  status: '待审核',
  img: ''
});

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  queryString: '',
  userType: '',
  status: ''
});

// 验证用户名是否存在
const checkUsernameExists = async (rule, value, callback) => {
  if (!value) {
    return callback(new Error('用户名为必填项'));
  }
  if (dialogStatus.value === 'update' && formData.userId) {
    // 如果是编辑状态且有userId，不进行重复性检测
    callback();
    return;
  }
  try {
    const response = await service.get('/admin/user/exists/username', { params: { username: value } });
    if (response.data.data) {
      ElMessage.error('用户名已存在');
      return callback(new Error('用户名已存在'));
    }
    callback();
  } catch (error) {
    console.error('检查用户名失败:', error);
    ElMessage.error('检查用户名时发生错误');
    callback(new Error('检查用户名时发生错误'));
  }
};

// 验证邮箱是否存在
const checkEmailExists = async (rule, value, callback) => {
  if (!value) {
    return callback(new Error('邮箱为必填项'));
  }
  if (dialogStatus.value === 'update' && formData.userId) {
    // 如果是编辑状态且有userId，不进行重复性检测
    callback();
    return;
  }
  try {
    const response = await service.get('/admin/user/exists/email', { params: { email: value } });
    if (response.data.data) {
      ElMessage.error('邮箱已存在');
      return callback(new Error('邮箱已存在'));
    }
    callback();
  } catch (error) {
    console.error('检查邮箱失败:', error);
    ElMessage.error('检查邮箱时发生错误');
    callback(new Error('检查邮箱时发生错误'));
  }
};

// 验证手机号是否存在
const checkPhoneExists = async (rule, value, callback) => {
  if (!value) {
    return callback(new Error('手机号为必填项'));
  }
  if (dialogStatus.value === 'update' && formData.userId) {
    // 如果是编辑状态且有userId，不进行重复性检测
    callback();
    return;
  }
  try {
    const response = await service.get('/admin/user/exists/phone', { params: { phone: value } });
    if (response.data.data) {
      ElMessage.error('手机号已存在');
    }
    callback();
  } catch (error) {
    console.error('检查手机号失败:', error);
    ElMessage.error('检查手机号时发生错误');
    callback(new Error('检查手机号时发生错误'));
  }
};

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '用户名为必填项', trigger: 'blur' },
    { validator: checkUsernameExists, trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码为必填项', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6-20个字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '邮箱为必填项', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
    { validator: checkEmailExists, trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '手机号为必填项', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
    { validator: checkPhoneExists, trigger: 'blur' }
  ],
  userType: [
    { required: true, message: '用户类型为必选项', trigger: 'change' }
  ],
  status: [
    { required: true, message: '状态为必选项', trigger: 'change' }
  ]
};

// 头像上传相关函数
const handleAvatarSuccess = (response) => {
  console.log('上传响应:', response);
  try {
    if (response && response.url) {
      console.log('上传成功的头像URL:', response.url);
      formData.img = response.url;
      ElMessage.success('头像上传成功');
      console.log('formData.img更新后:', formData.img); // 打印更新后的头像URL
    } else {
      console.error('上传响应格式错误:', response);
      ElMessage.error('上传失败：返回数据格式错误');
    }
  } catch (error) {
    console.error('处理上传响应失败:', error);
    ElMessage.error('头像上传失败');
  }
};

const handleAvatarError = (error, uploadFile) => {
  console.error('上传失败:', error);
  if (error.response) {
    const errorMsg = error.response.data?.error || '上传失败，请重试';
    ElMessage.error(errorMsg);
  } else {
    ElMessage.error('上传失败，请重试');
  }
};

const beforeAvatarUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type);
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG/GIF格式的图片!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return false;
  }
  return true;
};

// 获取用户类型标签样式
const getUserTypeTag = (type) => {
  const map = {
    '管理员': 'danger',
    '司机': 'warning',
    '客服': 'success',
    '乘客': 'info'
  };
  return map[type] || '';
};

// 获取状态标签样式
const getStatusTag = (status) => {
  const map = {
    '活跃': 'success',
    '禁用': 'danger',
    '待审核': 'warning'
  };
  return map[status] || '';
};

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return '--';
  return new Date(datetime).toLocaleString();
};

// 分页查询
const findPage = async (page = 1) => {
  loading.value = true;
  try {
    pagination.currentPage = page;
    const params = {
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize,
      queryString: pagination.queryString,
      userType: pagination.userType,
      status: pagination.status
    };
    const response = await service.get('/admin/user/page', { params });
    if (response.data.flag) {
      pagination.total = response.data.data.total;
      dataList.value = response.data.data.records;
    } else {
      ElMessage.error(response.data.message || '查询失败');
    }
  } catch (error) {
    console.error('查询失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    userId: null,
    username: '',
    password: '',
    email: '',
    phoneNumber: '',
    userType: '',
    status: '待审核',
    img: ''
  });
  if (dataForm.value) dataForm.value.resetFields();
};

// 新建按钮处理
const handleCreate = () => {
  dialogStatus.value = 'create';
  resetForm();
  dialogFormVisible.value = true;
};

// 添加用户
const handleAdd = async () => {
  const valid = await dataForm.value?.validate();
  if (valid) {
    try {
      dialogFormVisible.value = false;
      const response = await service.post('/admin/user', formData);
      if (response.data.flag) {
        ElMessage.success(response.data.message);
        findPage();
      } else {
        ElMessage.error(response.data.message);
      }
    } catch (error) {
      console.error('添加失败:', error);
      ElMessage.error('添加失败');
    }
  } else {
    ElMessage.error('表单验证失败，请检查输入项');
  }
};

// 编辑按钮处理
const handleUpdate = async (row) => {
  try {
    dialogStatus.value = 'update';
    const response = await service.get(`/admin/user/${row.userId}`);
    if (response.data.flag) {
      Object.assign(formData, response.data.data);
      dialogFormVisible.value = true;
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    console.error('获取详情失败:', error);
    ElMessage.error('获取详情失败');
  }
};

// 提交编辑
const handleEdit = () => {
  dataForm.value?.validate(async (valid) => {
    if (valid) {
      try {
        dialogFormVisible.value = false;
        const response = await service.put(`/admin/user/${formData.userId}`, formData);
        if (response.data.flag) {
          ElMessage.success(response.data.message);
          findPage();
        } else {
          ElMessage.error(response.data.message);
        }
      } catch (error) {
        console.error('更新失败:', error);
        ElMessage.error('更新失败');
      }
    }
  });
};

// 状态变更处理
const handleStatusChange = async (row) => {
  const newStatus = row.status === '禁用' ? '活跃' : '禁用';
  try {
    const response = await service.put(`/admin/user/${row.userId}/status`, { status: newStatus });
    if (response.data.flag) {
      ElMessage.success(response.data.message);
      findPage();
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    console.error('状态更新失败:', error);
    ElMessage.error('状态更新失败');
  }
};

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该用户吗？此操作不可恢复！', '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    try {
      const response = await service.delete(`/admin/user/${row.userId}`);
      if (response.data.flag) {
        ElMessage.success(response.data.message);
        findPage();
      } else {
        ElMessage.error(response.data.message);
      }
    } catch (error) {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {
    ElMessage.info('已取消删除操作');
  });
};

// 提交编辑或新增
const handleEditOrAdd = async () => {
  const valid = await dataForm.value?.validate();
  if (valid) {
    try {
      dialogFormVisible.value = false;
      if (dialogStatus.value === 'create') {
        // 新增用户
        const response = await service.post('/admin/user', formData);
        if (response.data.flag) {
          ElMessage.success(response.data.message);
          findPage();
        } else {
          ElMessage.error(response.data.message);
        }
      } else {
        // 编辑用户
        const response = await service.put(`/admin/user/${formData.userId}`, formData);
        if (response.data.flag) {
          ElMessage.success(response.data.message);
          findPage();
        } else {
          ElMessage.error(response.data.message);
        }
      }
    } catch (error) {
      console.error('操作失败:', error);
      ElMessage.error('操作失败');
    }
  } else {
    ElMessage.error('表单验证失败，请检查输入项');
  }
};




// 页面加载时执行查询
onMounted(() => {
  findPage();
});
</script>


<style scoped>
.filter-container {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.el-tag {
  margin-right: 5px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.img {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
</style>